<template>
    <!-- 查询表单 -->
    <div class="search-form">
        <el-card class="search-card">
            <div class="search-container">
                <div class="search-fields">
                    <div class="field-row">
                        <el-button type="success" class="!ml-0" plain @click="dialogFormVisible = true">新增</el-button>

                        <el-input v-model="page.TestProName" placeholder="请输入检测项目名称" class="search-input" clearable />
                    </div>
                </div>
                <div class="search-actions">
                    <el-button type="primary" @click="list" class="search-btn">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button type="info" @click="clearSearch" class="clear-btn">
                        <el-icon>
                            <Close />
                        </el-icon>
                        重置
                    </el-button>
                    <el-button type="warning" @click="toggleFullscreen" class="fullscreen-btn">
                        <el-icon>
                            <FullScreen />
                        </el-icon>
                        全屏
                    </el-button>
                </div>
            </div>
        </el-card>
    </div>
    <!-- 新增 -->
    <el-dialog v-model="dialogFormVisible" title="新增检验项目" width="600">
        <el-form :model="form" :rules="formRules" ref="formRef">
            <el-form-item label="名称" :label-width="formLabelWidth" prop="testProName">
                <el-input v-model="form.testProName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="检验类型" :label-width="formLabelWidth" prop="testProTypeId">
                <el-select v-model="form.testProTypeId" placeholder="请选择">
                    <el-option v-for="t in tableDataType" :label="t.testTypeName" :value="t.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="作业方式" :label-width="formLabelWidth" prop="testProWorkType">
                <el-select v-model="form.testProWorkType" placeholder="请选择">
                    <el-option label="机器检验" value="机器检验" />
                    <el-option label="人工检验" value="人工检验" />
                    <el-option label="理化检验" value="理化检验" />
                </el-select>
            </el-form-item>
            <el-form-item label="标准值" :label-width="formLabelWidth" prop="testProStandard">
                <el-input v-model="form.testProStandard" autocomplete="off" />
            </el-form-item>
            <el-form-item label="单位" :label-width="formLabelWidth" prop="testProUnit">
                <el-select v-model="form.testProUnit" placeholder="请选择">
                    <el-option v-for="u in tableDataunit" :label="u.unitName" :value="u.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="上限值" :label-width="formLabelWidth" prop="testProUpper">
                <el-input v-model="form.testProUpper" autocomplete="off" />
            </el-form-item>
            <el-form-item label="下限值" :label-width="formLabelWidth" prop="testProLower">
                <el-input v-model="form.testProLower" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input v-model="form.testProNote" type="textarea" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addpro">
                    添加
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog v-model="dialogUpdateVisible" title="修改检验项目" width="500">
        <el-form :model="updateform" :rules="formRules" ref="updateFormRef">
            <el-form-item label="名称" :label-width="formLabelWidth" prop="testProName">
                <el-input v-model="updateform.testProName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="检验类型" :label-width="formLabelWidth" prop="testProTypeId">
                <el-select v-model="updateform.testProTypeId" placeholder="请选择">
                    <el-option v-for="t in tableDataType" :label="t.testTypeName" :value="t.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="作业方式" :label-width="formLabelWidth" prop="testProWorkType">
                <el-select v-model="updateform.testProWorkType" placeholder="请选择">
                    <el-option label="机器检验" value="机器检验" />
                    <el-option label="人工检验" value="人工检验" />
                    <el-option label="理化检验" value="理化检验" />
                </el-select>
            </el-form-item>
            <el-form-item label="标准值" :label-width="formLabelWidth" prop="testProStandard">
                <el-input v-model="updateform.testProStandard" autocomplete="off" />
            </el-form-item>
            <el-form-item label="单位" :label-width="formLabelWidth" prop="testProUnit">
                <el-select v-model="updateform.testProUnit" placeholder="请选择">
                    <el-option v-for="u in tableDataunit" :label="u.unitName" :value="u.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="上限值" :label-width="formLabelWidth" prop="testProUpper">
                <el-input v-model="updateform.testProUpper" autocomplete="off" />
            </el-form-item>
            <el-form-item label="下限值" :label-width="formLabelWidth" prop="testProLower">
                <el-input v-model="updateform.testProLower" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input v-model="updateform.testProNote" type="textarea" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogUpdateVisible = false">取消</el-button>
                <el-button type="primary" @click="update">
                    修改
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed type="index" label="序号" width="70" />
        <el-table-column prop="testProName" label="检测项目名称" width="120" />
        <el-table-column prop="testTypeName" label="检测类型" width="100" />
        <el-table-column prop="testProWorkType" label="检测方式" width="100" />
        <el-table-column prop="testProStandard" label="标准值" width="80" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="testProUpper" label="上限值" width="80" />
        <el-table-column prop="testProLower" label="下限值" width="80" />
        <el-table-column prop="testProNote" label="备注" width="180" />
        <el-table-column prop="addProp" label="创建人" width="100" />
        <el-table-column prop="addTime" label="创建时间" width="200">
            <template #default="scope">
                {{ moment(scope.row.addTime).format("YYYY年MM月DD日 hh:mm:ss") }}
            </template>
        </el-table-column>
        <el-table-column prop="updTime" label="修改时间" width="200">
            <template #default="scope">
                <span v-if="scope.row.updTime == null"></span>
                <span v-if="scope.row.updTime != null">{{ moment(scope.row.updTime).format("YYYY年MM月DD日 hh:mm:ss")
                    }}</span>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">
                    删除
                </el-button>
                <el-button link type="primary" size="small" @click="updateType(scope.row)">修改</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 自定义分页组件 -->
    <div class="pagination-container">
        <div class="pagination-card">
            <div class="pagination-left">
                <span class="total-text">共{{ page.count }}条数据</span>
            </div>
            <div class="pagination-right">
                <span class="total-count">共{{ page.count }}条</span>
                <el-select v-model="page.Pagesize" @change="list()" class="page-size-select">
                    <el-option label="5条/页" :value="5" />
                    <el-option label="10条/页" :value="10" />
                    <el-option label="15条/页" :value="15" />
                    <el-option label="20条/页" :value="20" />
                </el-select>
                <div class="page-navigation">
                    <el-button :disabled="page.Pageindex <= 1" @click="page.Pageindex = page.Pageindex - 1; list()"
                        class="nav-btn">
                        上一页
                    </el-button>

                    <!-- 显示页码 -->
                    <template v-for="p in displayPages" :key="p">
                        <el-button class="page-btn" :class="{ active: p === page.Pageindex }" @click="goToPage(p)">{{ p
                            }}</el-button>
                    </template>

                    <!-- 省略号 -->
                    <span v-if="totalPages > 3 && page.Pageindex < totalPages - 2" class="ellipsis">...</span>

                    <!-- 最后一页 -->
                    <el-button v-if="totalPages > 3 && page.Pageindex < totalPages - 2" class="page-btn"
                        @click="goToPage(totalPages)">{{ totalPages }}</el-button>

                    <el-button :disabled="page.Pageindex >= Math.ceil(page.count / page.Pagesize)"
                        @click="page.Pageindex = page.Pageindex + 1; list()" class="nav-btn">
                        下一页
                    </el-button>
                </div>
                <div class="page-jumper">
                    <span>前往</span>
                    <el-input v-model="jumpPage" @keyup.enter="jumpToPage" class="jump-input" />
                    <span>页</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import Maxios from '@/Http/MesHelp';
import moment from 'moment';
import { onMounted, ref, computed } from 'vue';
import { Search, Close, ArrowLeft, ArrowRight, FullScreen } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { message } from 'ant-design-vue';

const dialogFormVisible = ref(false)
const dialogUpdateVisible = ref(false)
const isFullscreen = ref(false)
const formLabelWidth = '140px'
const jumpPage = ref(1)
const formRef = ref()
const updateFormRef = ref()

// 正整数验证规则
const positiveIntegerValidator = (rule: any, value: any, callback: any) => {
    if (value === null || value === undefined || value === '') {
        callback()
        return
    }
    const num = Number(value)
    if (isNaN(num) || !Number.isInteger(num) || num <= 0) {
        callback(new Error('请输入正整数'))
    } else {
        callback()
    }
}

// 表单验证规则
const formRules = {
    testProName: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    testProTypeId: [
        { required: true, message: '请选择检验类型', trigger: 'change' }
    ],
    testProWorkType: [
        { required: true, message: '请选择作业方式', trigger: 'change' }
    ],
    testProStandard: [
        { validator: positiveIntegerValidator, trigger: 'blur' }
    ],
    testProUnit: [
        { required: true, message: '请选择单位', trigger: 'change' }
    ],
    testProUpper: [
        { validator: positiveIntegerValidator, trigger: 'blur' }
    ],
    testProLower: [
        { validator: positiveIntegerValidator, trigger: 'blur' }
    ]
}

const form = ref({
    "testProName": "",
    "testProTypeId": null,
    "testProWorkType": "",
    "testProStandard": null,
    "testProUnit": null,
    "testProUpper": null,
    "testProLower": null,
    "testProNote": "",
    "addProp": ""
})

//添加
const addpro = () => {
    if (!formRef.value) return
    formRef.value.validate((valid: boolean) => {
        if (!valid) return
        Maxios.post("/api/TestProject/AddProject", form.value).then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message)
                dialogFormVisible.value = false
                form.value.addProp = ''
                form.value.testProName = ''
                form.value.testProTypeId = null
                form.value.testProWorkType = ''
                form.value.testProStandard = null
                form.value.testProUnit = null
                form.value.testProUpper = null
                form.value.testProLower = null
                form.value.testProNote = ''
                form.value.addProp = ''
                list()
            }
            else {
                ElMessage.error(res.data.message)
            }
        })
    })
}

//删除
const handleClick = (id: any) => {
    ElMessageBox.confirm(
        '确定要逻辑删除本条数据吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        Maxios.post("/api/TestProject/DeleteProject", { id: id }).then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message)
                list()
            }
            else {
                ElMessage.error(res.data.message)
            }
        })
    })


}

const tableData = ref([])
const tableDataunit = ref([
    {
        "unitName": "",
        "id": null,
    },
])
const tableDataType = ref([
    {
        "id": 0,
        "testTypeCode": "",
        "testTypeName": "",
        "testTypeDesc": "",
        "addProp": "",
        "addTime": "",
        "updTime": ""
    }
])

const page = ref({
    Pageindex: 1,
    Pagesize: 10,
    TestProName: "",
    count: 0,
    page: 0
})

//项目显示
const list = () => {
    Maxios.get("/api/TestProject/ListProject", { params: page.value }).then(res => {
        tableData.value = res.data.data.list

        page.value.count = res.data.data.count
        page.value.page = res.data.data.page
    })
}

// 清空搜索条件
const clearSearch = () => {
    page.value.TestProName = ''
    page.value.Pageindex = 1
    list()
}

// 全屏切换
const toggleFullscreen = () => {
    isFullscreen.value = !isFullscreen.value
    if (isFullscreen.value) {
        // 进入全屏
        const element = document.documentElement
        if (element.requestFullscreen) {
            element.requestFullscreen()
        } else if ((element as any).webkitRequestFullscreen) {
            (element as any).webkitRequestFullscreen()
        } else if ((element as any).msRequestFullscreen) {
            (element as any).msRequestFullscreen()
        }
    } else {
        // 退出全屏
        if (document.exitFullscreen) {
            document.exitFullscreen()
        } else if ((document as any).webkitExitFullscreen) {
            (document as any).webkitExitFullscreen()
        } else if ((document as any).msExitFullscreen) {
            (document as any).msExitFullscreen()
        }
    }
}

// 跳转到指定页面
const jumpToPage = () => {
    const totalPages = Math.ceil(page.value.count / page.value.Pagesize)
    if (jumpPage.value >= 1 && jumpPage.value <= totalPages) {
        page.value.Pageindex = jumpPage.value
        list()
    } else {
        ElMessage.warning(`请输入1到${totalPages}之间的页码`)
    }
}

// 计算总页数与展示页码
const totalPages = computed(() => Math.max(1, Math.ceil(page.value.count / page.value.Pagesize)))

const displayPages = computed(() => {
    const total = totalPages.value
    const current = page.value.Pageindex

    if (total <= 3) {
        // 总页数小于等于3，显示所有页
        return Array.from({ length: total }, (_, i) => i + 1)
    }

    if (current <= 3) {
        // 当前页在前3页，显示前3页
        return [1, 2, 3]
    }

    if (current >= total - 2) {
        // 当前页在后3页，显示后3页
        return [total - 2, total - 1, total]
    }

    // 当前页在中间，显示当前页前后各1页
    return [current - 1, current, current + 1]
})

const goToPage = (p: number) => {
    if (p < 1 || p > totalPages.value) return
    page.value.Pageindex = p
    list()
}

const updateform = ref({
    "id": 0,
    "testProName": "",
    "testProTypeId": null,
    "testProWorkType": "",
    "testProStandard": null,
    "testProUnit": null,
    "testProUpper": null,
    "testProLower": null,
    "testProNote": ""
})

const updateType = (row: any) => {
    updateform.value.id = row.id
    updateform.value.testProName = row.testProName
    updateform.value.testProWorkType = row.testProWorkType
    updateform.value.testProTypeId = row.testProTypeId
    updateform.value.testProStandard = row.testProStandard
    updateform.value.testProUnit = row.testProUnit
    updateform.value.testProUpper = row.testProUpper
    updateform.value.testProLower = row.testProLower
    updateform.value.testProNote = row.testProNote
    dialogUpdateVisible.value = true
}

const update = () => {
    if (!updateFormRef.value) return
    updateFormRef.value.validate((valid: boolean) => {
        if (!valid) return
        Maxios.post("/api/TestProject/UpdateProject", updateform.value).then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message)
                dialogUpdateVisible.value = false
                list()
            }
            else {
                ElMessage.error(res.data.message)
            }
        })
    })
}

const pagetype = ref({
    Pageindex: 1,
    Pagesize: 10,
    TestTypeCode: "",
    TestTypeName: "",
    count: 0,
    page: 0
})

//显示
const listtype = () => {
    Maxios.get("/api/TestType/ListTestType", { params: pagetype.value }).then(res => {
        tableDataType.value = res.data.data.list

        pagetype.value.count = res.data.data.count
        pagetype.value.page = res.data.data.page
    })
}

//显示单位
const listunit = () => {
    Maxios.post("/api/Band/UnitGet").then(res => {
        tableDataunit.value = res.data.data
    })
}

onMounted(() => {
    list()
    listtype()
    listunit()
})
</script>

<style scoped>
.search-form {
    margin-bottom: 20px;
}

.search-card {
    background: #f5f5f5;
    border-radius: 8px;
}

.search-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
}

.search-fields {
    flex: 1;
}

.field-row {
    display: flex;
    gap: 16px;
    align-items: center;
}

.search-input {
    width: 200px;
}

.search-input :deep(.el-input__wrapper) {
    border-radius: 6px;
    background: white;
}

.search-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}

.clear-btn {
    background: #f0f0f0;
    border: 1px solid #d9d9d9;
    color: #666;
    border-radius: 6px;
}

.clear-btn:hover {
    background: #e6e6e6;
    border-color: #bfbfbf;
}

.fullscreen-btn {
    background: #fdf6ec;
    border: 1px solid #f5dab1;
    color: #e6a23c;
    border-radius: 6px;
}

.fullscreen-btn:hover {
    background: #faecd8;
    border-color: #eebe77;
    color: #d48806;
}

.search-btn {
    border-radius: 6px;
}

.search-btn:hover {
    opacity: 0.8;
}

/* 分页组件样式 */
.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    width: 100%;
    overflow-x: auto;
}

.pagination-card {
    background: white;
    border-radius: 8px;
    padding: 16px 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    max-width: 100%;
    min-width: 600px;
    flex-wrap: wrap;
    gap: 16px;
}

.pagination-left {
    display: flex;
    align-items: center;
    flex-shrink: 0;
}

.total-text {
    font-size: 14px;
    color: #666;
    font-weight: 500;
    white-space: nowrap;
}

.pagination-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
    justify-content: flex-end;
}

.total-count {
    font-size: 14px;
    color: #666;
    white-space: nowrap;
}

.page-size-select {
    width: 100px;
    flex-shrink: 0;
}

.page-size-select :deep(.el-input__wrapper) {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
}

.page-navigation {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
}

.nav-btn {
    width: 32px;
    height: 32px;
    padding: 0;
    border-radius: 4px;
    border: none;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.nav-btn:hover:not(:disabled) {
    color: #409eff;
}

.nav-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.current-page {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: #409eff;
    color: white;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    flex-shrink: 0;
}

.page-btn {
    width: 32px;
    height: 32px;
    padding: 0;
    border-radius: 4px;
    border: none;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    font-size: 14px;
    color: #606266;
}

.page-btn:hover {
    color: #409eff;
}

.page-btn.active {
    background: #409eff;
    color: white;
}

.ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    color: #c0c4cc;
    font-size: 14px;
    flex-shrink: 0;
}

.page-jumper {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: #666;
    flex-shrink: 0;
}

.jump-input {
    width: 60px;
}

.jump-input :deep(.el-input__wrapper) {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .pagination-card {
        padding: 12px 16px;
        gap: 12px;
    }

    .pagination-right {
        gap: 8px;
    }

    .total-count {
        display: none;
    }
}

@media (max-width: 768px) {
    .pagination-container {
        justify-content: flex-start;
        padding: 0 16px;
    }

    .pagination-card {
        min-width: 100%;
        padding: 12px;
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }

    .pagination-left {
        justify-content: center;
    }

    .pagination-right {
        justify-content: center;
        flex-wrap: wrap;
        gap: 8px;
    }

    .page-size-select {
        width: 80px;
    }

    .jump-input {
        width: 50px;
    }
}

@media (max-width: 480px) {
    .pagination-right {
        flex-direction: column;
        align-items: center;
        gap: 8px;
    }

    .page-navigation {
        order: 1;
    }

    .page-size-select {
        order: 2;
    }

    .page-jumper {
        order: 3;
    }
}
</style>
